package djrain.lilochat.client;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import android.location.Location;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

public class SocketClient
{
	BufferedReader br = null;
	BufferedWriter bw = null;
	// String server = "192.168.20.10";
	String server = "bluemobile.iptime.org";
	int port = 5777;
	private Socket socket;
	private Handler handler;

	public boolean connectServer(Handler handler)
	{
		this.handler = handler;
		try
		{
			socket = new Socket();
			SocketAddress sockaddr = new InetSocketAddress(server, port);
			socket.connect(sockaddr, 1000);
			br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
			bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));

			new ReceiveMessage().start();

			return true;
		}
		catch (UnknownHostException e)
		{
			e.printStackTrace();
			return false;
		}
		catch (SocketTimeoutException e)
		{
			e.printStackTrace();
			return false;
		}
		catch (IOException e)
		{
			e.printStackTrace();
			return false;
		}
	}

	public void close()
	{
		try
		{
			bw.close();
			br.close();
			socket.close();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}



	private synchronized void addReceiveString(String string)
	{
		Log.e("addReceiveString0", string);
//		this.receiveString.append(string);
		
		LiloMessage.sendMessage(handler, string);
		
//		handler.sendEmptyMessage(0);
		
//		Log.e("addReceiveString1", receiveString.toString());
	}

	class ReceiveMessage extends Thread
	{

		public void run()
		{
			while (true)
			{
				try
				{
					addReceiveString(br.readLine());
				}
				catch (IOException e)
				{
				}
			} // end of while
		} // end of run ()
	} // end of class ReceiveMessage

	public boolean sendMessage(String msg)
	{
		try
		{
			bw.write(msg);
			bw.newLine();
			bw.flush();
			Log.e("Lilo", ">" + msg);
			return true;
		}
		catch (UnknownHostException e)
		{
			e.printStackTrace();
			return false;
		}
		catch (SocketTimeoutException e)
		{
			e.printStackTrace();
			return false;
		}
		catch (IOException e)
		{
			e.printStackTrace();
			return false;
		}

	}

	public void sendIam(String displayname, Location lastLoaction)
	{
		sendMessage("/iam " + displayname);
		sendLilo(lastLoaction);
	}

	public void sendLilo(Location location)
	{
		if (location == null)
			return;
		sendMessage("/@   " + location.getLongitude() + ":" + location.getLatitude());
	}
}
